package me.zhengjie.modules.system.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WeChatQRCodeGenerator {

    // 生成二维码图片
    public static void generateQRCode(String content, String filePath, int width, int height) throws IOException, WriterException {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                image.setRGB(x, y, matrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }

        File qrFile = new File(filePath);
        ImageIO.write(image, "png", qrFile);
    }

    public static void main(String[] args) {
        String content = "http://your-wechat-promotion-url.com"; // 替换成您的微信推广链接
        String filePath = "C:\\Users\\Administrator\\Desktop\\imgCode\\tset111.png"; // 生成的二维码文件路径
        int width = 300; // 二维码宽度
        int height = 300; // 二维码高度
        try {
            generateQRCode(content, filePath, width, height);
            System.out.println("微信推广码已生成：" + filePath);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
        }
    }
}